package com.andriology.ui;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.andriology.logic.Test;
import com.andriology.logic.TestQuestion;
import com.andriology.logic.TestResult;
import com.andriology.ommar_el_ard.R;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.actionbarsherlock.view.MenuItem;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Tracker;
import com.viewpagerindicator.TitlePageIndicator;

public class TestActivity extends SherlockFragmentActivity {

	/* start this activity such that it is created for only one time, it will need:
	 * 1- test number
	 * 2- test title
	 * 3- question number in the test 
	 * such that each time user swipes, it loads the relevant question without wasting a lot of memory resources*/
	static private Test test;

    
	static TextView testTitle;
	static TextView txtViewQuestion;
	static TestResult testResultInfo;
	
	private static String [] TITLES ;
	
	int previousSelectedIndex;
	
	/* 0 = alert dialog is not called for this question before, 1 = alert dialog is called for this question, 2 = alert dialog should neve ever called again*/
	static int isAlertDialogCalled; 
	static ViewPager viewPager;
    
	private static Tracker myTracker;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Set context */
		EasyTracker.getInstance().setContext(getApplicationContext());
		/* Instantiate the Tracker */
		myTracker = EasyTracker.getTracker();


		previousSelectedIndex = 0;
		isAlertDialogCalled = 0;

		setContentView(R.layout.activity_swipey_tab);

		/* Home App Icon can preceded by arrow for up navigation using two ways:
		 * 1. Use homeAsUp in display options xml attribute in styles.xml but this really draws the arrow but icon is not clickable except for Android 4.1
		 * 2. Use setDisplayHomeAsUpEnabled explicitly and thus the app icon is clickable for all android versions */
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
			
		/*get test number to be run*/
		test = getIntent().getParcelableExtra("parcel");
		testResultInfo = test.getResultTestInfo();

		switch(test.getNumOfQuestions()){
		case 7:
			TITLES = getResources().getStringArray(R.array.seven_questions_titles);
			break;
		case 8:
			TITLES = getResources().getStringArray(R.array.eight_questions_titles);
			break;
		case 9:
			TITLES = getResources().getStringArray(R.array.nine_questions_titles);
			break;
		default:
			throw(null);
		}

		/* Google_Analytics*/
		myTracker.setCustomDimension(1, test.getTestTitle());
		myTracker.sendView("Test Screen");
		
		int numOfQuestions = test.getNumOfQuestions();
		int ActualResults[];

		switch (numOfQuestions) {
		case 7:
			ActualResults = getResources().getIntArray(R.array.seven_questions_final_percents);
			break;
		case 8:
			ActualResults = getResources().getIntArray(R.array.eight_questions_final_percents);
			break;
		case 9:
			ActualResults = getResources().getIntArray(R.array.nine_questions_final_percents);
			break;
		default:
			throw(null);
		}

		testResultInfo.setFinalResultPathMap(ActualResults, numOfQuestions);

		MyAdapter pagerAdapter = new MyAdapter(getSupportFragmentManager());
		/* Number of pages = number of questions/test + one page for the result */
		pagerAdapter.setNumOfPages(test.getNumOfQuestions() + 1);

		viewPager = (ViewPager) findViewById(R.id.view_pager_id);
		viewPager.setAdapter(pagerAdapter);

		TitlePageIndicator titleIndicator = (TitlePageIndicator)findViewById(R.id.swipey_tabs_id);
		titleIndicator.setViewPager(viewPager);
		viewPager.setCurrentItem(0);

		titleIndicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

			@Override
			public void onPageSelected(int index) {
				int previousIndex;
				int myWeigth;
				
				if(previousSelectedIndex < test.getNumOfQuestions()){
					previousIndex = previousSelectedIndex;
				}
				else{
					previousIndex = previousSelectedIndex - 1;
				}
				
				myWeigth = test.getQuestion(previousIndex).getChosenAnswerWeight();

				/* swiping forward*/
				if ((index-previousIndex)>= 0){
					isPreviousQuestionAnswered(index, myWeigth);
				}
				else{
					isAlertDialogCalled = 0;
				}
				
				previousSelectedIndex = index;
				
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

		});
	}

	private void isPreviousQuestionAnswered(int index, int myWeigth) {
		if (( myWeigth== TestQuestion.INITIAL_WEIGTH) && (isAlertDialogCalled == 0)){
			NoAnswerAlertDialogFragment alertDiag = new NoAnswerAlertDialogFragment();

			Bundle bundle = new Bundle();
			bundle.putInt("SelectedIndex", index);

			alertDiag.setArguments(bundle);
			alertDiag.show(getSupportFragmentManager(), "NoAnswerAlertDialogTag");
		}
		else{
			isAlertDialogCalled = 0;
		}
	}
	
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	Intent intent;
    	switch (item.getItemId()) {
    	case android.R.id.home:
    		/*TODO: Try this out: NavUtils.navigateUpFromSameTask(this);*/
    		/*app icon in action bar clicked; go home*/
    		
    		intent = new Intent(this, MainActivity.class);
    		
            /* With this flag, if the activity you're starting already exists in the current task, 
             * then all activities on top of it are destroyed and it is brought to the front.
             * you should usually not create a new instance of the home activity. Otherwise, 
             * you might end up with a long stack of activities in the current task with multiple 
             * instances of the home activity.*/
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            break;
    	default:
			return super.onOptionsItemSelected(item);
		}
    	return true;
    }
    
    public static class MyAdapter extends FragmentPagerAdapter {
    	int numOfPages = -1;
		public MyAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			
			/* You can switch on position to load different pages*/
			if (position == test.getNumOfQuestions())
			{
				return ResultFragment.newInstance();
			}
			else
			{
				/* ListFragment is child of Fragment class, hence it can be returned in getItem method.
				 * In fact, it represents a Fragment that hosts a list of views*/
				
				return ArrayListFragment.newInstance(position);
			}
		}

		@Override
		public int getCount() {
			return numOfPages;
		}
    	
		public void setNumOfPages (int num) {
			numOfPages = num;
		}
		
		@Override
		public CharSequence getPageTitle(int position) {
			return TITLES[position];
		}
    }
    
    /* ListFragment: is a fragment that hosts a list of views, where these views can be just simple single line to customized layout views 
     * Here each Page can be considered as ListFragment since it will host a question with a list of 3 views where each view is a radio button choice
     */
    public static class ArrayListFragment extends ListFragment{
    	int mNum;
    	TestQuestion testQuestion;
    	
    	/* Create a new instance of a fragment, providing "num" as an argument.
    	 * Note that you have to import v4.ListFragment otherwise you will get a compilation error for type casting ArrayList to Fragment in
    	 * getItem method*/
    	
    	static ArrayListFragment newInstance (int num) {
    		ArrayListFragment f = new ArrayListFragment();
    		Bundle args = new Bundle();
    		args.putInt("fragment_num", num);
    		f.setArguments(args);
    		
    		return f;
    	}
    	
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		mNum = (getArguments() != null) ? getArguments().getInt("fragment_num") : 0 ;
    	}
    	
    	
    	@Override
    	public View onCreateView(LayoutInflater inflater, ViewGroup container,
    			Bundle savedInstanceState) {

    		test.setCurrentQuestIndex(mNum);
    		testQuestion = test.getCurrentQuestion();
			
    		View view = inflater.inflate(R.layout.fragment_pager_question, container, false);
    		loadViewObjects(view);
    		setViewObjects(testQuestion);
    		return view;
    	}

    	@Override
    	public void onActivityCreated(Bundle savedInstanceState) {
    		super.onActivityCreated(savedInstanceState);
    		
    		/* each item in this list view is not a simple item but instead it is a radio button i.e. single choice*/
    		setListAdapter(new ArrayAdapter<String>(getActivity(),R.layout.custom_simple_list_item_single_choice , testQuestion.getChoices()));
    	}

    	@Override
    	public void onListItemClick(ListView l, View v, int position, long id) {
    		int answer_index ;
    		int previousAnswerWeight;
    		int currentAnswerWeight;
    		
    		switch (position) {
			case TestQuestion.INDEX_OF_CHOICE_1:
				answer_index = TestQuestion.INDEX_OF_CHOICE_1;
				break;
			case TestQuestion.INDEX_OF_CHOICE_2:
				answer_index = TestQuestion.INDEX_OF_CHOICE_2;
				break;
			case TestQuestion.INDEX_OF_CHOICE_3:
				answer_index = TestQuestion.INDEX_OF_CHOICE_3;
				break;

			default:
				throw(null);
			}
    		
    		previousAnswerWeight 	= testQuestion.getChosenAnswerWeight();
    		currentAnswerWeight 	= testQuestion.getchoicesWeights()[answer_index];
    		testQuestion.setChosenAnswerWeight(currentAnswerWeight);
    		/*test.getResultTestInfo().addValue(current_answer_value - previous_answer_value);*/
    		
    		if (previousAnswerWeight != currentAnswerWeight)
    		{
    			/* increment corresponding high/low number of answers, since this will affect the final result at the end.*/
    			switch (currentAnswerWeight) {
    			case TestQuestion.LOW_WEIGHT:
    				testResultInfo.incNumOfLowWeightedAnswers();
    				break;
    			case TestQuestion.MID_WEIGHT:
    				testResultInfo.incNumOfMiddleWeightedAnswers();
    				break;
    			case TestQuestion.HIGH_WEIGHT:
    				testResultInfo.incNumOfHighlyWeightedAnswers();
    				break;

    			default:
    				throw(null);
    			}
    			
    			/* decrement corresponding high/mid/low number of answers*/
    			switch (previousAnswerWeight) {
    			case TestQuestion.INITIAL_WEIGTH:
    				/* Do nothing*/
    				break;
    			case TestQuestion.LOW_WEIGHT:
    				testResultInfo.decNumOfLowWeightedAnswers();
    				break;
    			case TestQuestion.MID_WEIGHT:
    				testResultInfo.decNumOfMiddleWeightedAnswers();
    				break;
    			case TestQuestion.HIGH_WEIGHT:
    				testResultInfo.decNumOfHighlyWeightedAnswers();
    				break;

    			default:
    				throw(null);
    			}
    			
    			
    			/* Since page viewer mechanism prepares the next page to be displayed,so
    			 * assume number of pages are N, so the last page (result page) will be prepared without taking into account the answer of the last
    			 * question so we should have update the result accordingly*/
    			if(mNum == test.getNumOfQuestions()-1){
    				ResultFragment.updateLastResult();
    				
    				myTracker.setCustomDimension(1, test.getTestTitle());
    				myTracker.setCustomDimension(2, String.valueOf(test.getResultTestInfo().getFinalResult()));
    				/* Send Result to Google_Analytics reports */
    				myTracker.sendView("Result Screen");

    			}
    		}
    		
    		/*int x = testResultInfo.getNumOfHighlyWeightedAnswers();
    		int y = testResultInfo.getNumOfMiddleWeightedAnswers();
    		
    		Toast.makeText(getActivity(),"Result" + testResultInfo.getMappedFinalResultPercent(x, y) , Toast.LENGTH_SHORT).show();*/
    		
    	}
    	
    	public void loadViewObjects (View view){
    		testTitle		= (TextView)view.findViewById(R.id.txtViewTestTitle);
    		txtViewQuestion = (TextView)view.findViewById(R.id.txtViewQuestion);
    	}
    	
    	public void setViewObjects(TestQuestion testQuestion){
    		
    		testTitle.setText(test.getTestTitle());
    		txtViewQuestion.setText(testQuestion.getQuestion());

    	}
    }

    public static class ResultFragment extends Fragment{
    	
    	private static TextView txtViewResultPercent;
    	private static TextView txtViewResultMsg;
    	private static TextView txtViewAdviceMsg;
    	private ImageView imgViewThumbnail;
    	
    	static ResultFragment newInstance () {
    		ResultFragment f = new ResultFragment();
    		
    		return f;
    	}
    	
    	@Override
    	public View onCreateView(LayoutInflater inflater, ViewGroup container,
    			Bundle savedInstanceState) {
    		
    		View view = inflater.inflate(R.layout.activity_result, container, false);
    		loadViewObjects(view);
    		
            updateLastResult();
            String []youtubeVideoIds = getResources().getStringArray(R.array.youtube_video_ids);
            final String youTubeVideoWebPath = getResources().getString(R.string.video_url_prefix)+
            								youtubeVideoIds[test.getTestNumber() - 1];
            /*Once the video view is touched by down press gesture, play the video*/
            imgViewThumbnail.setOnClickListener(new View.OnClickListener() {
    			
    			@Override
    			public void onClick(View v) {

    				Intent intent= new Intent(Intent.ACTION_VIEW, Uri.parse(youTubeVideoWebPath));
    				startActivity(intent);
    			}
    		});

            String testNum = (test.getTestNumber() <=9 ? "0":"") +test.getTestNumber();
            String resourceName = getResources().getString(R.string.video_img_resource_prefix) + testNum;
            int resourceImgId = getResources().getIdentifier(resourceName, "drawable", getActivity().getPackageName());
            imgViewThumbnail.setImageResource(resourceImgId);
    		return view;
    	}
    	
    	public static void updateLastResult()
    	{
    		int x = testResultInfo.getNumOfHighlyWeightedAnswers();
    		int y = testResultInfo.getNumOfMiddleWeightedAnswers();
    		int z = testResultInfo.getNumOfLowWeightedAnswers();
    		
    		if((x+y+z)== test.getNumOfQuestions())
    		{
	    		int result = testResultInfo.getMappedFinalResultPercent(x,y);
	    		testResultInfo.setFinalResult(result);
	    		
	            txtViewResultPercent.setText(String.valueOf(result)+ "%");
	            txtViewResultMsg.setText(testResultInfo.getRangeMessage(result));
	            txtViewAdviceMsg.setText(testResultInfo.getRangeAdvice(result));
    		}
    	}

		private void loadViewObjects(View view){
            txtViewResultPercent = (TextView)view.findViewById(R.id.txtViewResultPercent);
            txtViewResultMsg 	 = (TextView)view.findViewById(R.id.txtViewResultMsg);
            txtViewAdviceMsg 	 = (TextView)view.findViewById(R.id.txtViewAdviceMsg);
            imgViewThumbnail 	= (ImageView) view.findViewById(R.id.img_view_thumbnail);
        }
    }
    
    public class NoAnswerAlertDialogFragment extends DialogFragment {
		
	    @Override
	    public Dialog onCreateDialog(Bundle savedInstanceState) {
	    	
	    	final int selectedIndex = getArguments().getInt("SelectedIndex");
	    	final int index  = (selectedIndex == 0)? selectedIndex:selectedIndex-1;
	    	
	        // Use the Builder class for convenient dialog construction
	        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
	        builder.setMessage(R.string.no_answer_alert_msg)
	               .setPositiveButton(R.string.no_answer_alert_ok, new DialogInterface.OnClickListener() {
	                   public void onClick(DialogInterface dialog, int id) {
	                	   isAlertDialogCalled = 1;
	                	   viewPager.setCurrentItem(index);
	                   }
	               });
	        
	        // Create the AlertDialog object and return it
	        return builder.create();
	    }
    }
}
